package com.xingda.packing.task.listener;

import com.xingda.packing.domain.PackProductionLine;
import com.xingda.packing.domain.ProductBoxLocation;
import com.xingda.packing.enums.TaskState;
import com.xingda.packing.enums.TaskType;
import com.xingda.packing.task.ticket.PackingTicket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Optional;

@Slf4j
@Component
public class PackingListener implements TaskListenerService {
    @Override
    public boolean accept(PackProductionLine productionLine, int area) {
        return checkTask(productionLine.getRobot().getTaskTicket(area), TaskType.PACKING);
    }

    @Override
    public void monitor(PackProductionLine productionLine, int area) {
        if (productionLine.getRobot().isGrabComplete(area)) {
            productionLine.getRobot().resetGrabState(area);
        }

        if (productionLine.getRobot().isPalletizingComplete(area)) {
            productionLine.getRobot().clear(area);
            PackingTicket ticket = (PackingTicket) productionLine.getRobot().getTaskTicket(area);
            int boxLocationNo = ticket.getTag();
            Optional<ProductBoxLocation> pblOptional = productionLine.getProductArea().getProductBoxLocation(boxLocationNo);
            if (pblOptional.isPresent() && Objects.nonNull(pblOptional.get().getBox())) {
                pblOptional.get().getBox().putWheel(ticket.getWheel());
            }
            ticket.setState(TaskState.FINISH);
            productionLine.getRobot().listenerPackingEvent(ticket, area);
        }
    }
}
